/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package taikai.draws;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import taikai.TeamOrPlayer;
import taikai.TeamsOrPlayers;
import taikai.TeamOrPlayerForARound;
import taikai.MatchesData;

public class KnockoutDrawStrategy implements DrawStrategy, Serializable {

    private final TeamsOrPlayers teamsOrPlayers;
    private int matchLength;
    private int changeOverTime;
    private final SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");

    public KnockoutDrawStrategy(TeamsOrPlayers teamsOrPlayers) {
        this.teamsOrPlayers = teamsOrPlayers;
    }

    @Override
    public String getName() {
        return "Knockout";
    }

    private int estimateRunningTime() {
        return (teamsOrPlayers.getSize() - 1) * (matchLength + changeOverTime);
    }

    @Override
    public void generateMatches(MatchesData matches) {
        final int size = teamsOrPlayers.getSize();

        for (int i = 0; i < size; i += 2) {
            final TeamOrPlayer red = teamsOrPlayers.getTeamOrPlayer(i);
            final TeamOrPlayer white;
            if (i + 1 >= size) {
                white = red;
            } else {
                white = teamsOrPlayers.getTeamOrPlayer(i + 1);
            }
            matches.add(new TeamOrPlayerForARound(red, white));
        }
    }

    @Override
    public void setMatchLength(int matchLength) {
        this.matchLength = matchLength;
    }

    @Override
    public void setChangeOverTime(int changeOverTime) {
        this.changeOverTime = changeOverTime;
    }

    @Override
    public int getMatchLength() {
        return matchLength;
    }

    @Override
    public int getChangeOverTime() {
        return changeOverTime;
    }

    @Override
    public String getEstimatedRunningTime() {
        Calendar cal = Calendar.getInstance();
        cal.set(0, 0, 0, 0, 0, 0);
        cal.add(Calendar.MINUTE, estimateRunningTime());
        return format.format(cal.getTime());
    }
}
